/*
 * Android Runner is a multiplayer GPS game fully written by Xurxo Mendez Perez
 * 
 * Copyright (C) 2009 Xurxo Mendez Perez
 *   
 * This file is part of Android Runner.
 * 
 * Android Runner is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Android Runner is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Android Runner.  If not, see <http://www.gnu.org/licenses/>.
 */

package es.sonxurxo.gpsgame.client.cv.activity;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.location.Address;
import android.location.Geocoder;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import es.sonxurxo.gpsgame.client.R;
import es.sonxurxo.gpsgame.client.cv.common.actions.CommonActions;
import es.sonxurxo.gpsgame.client.cv.common.dialogs.CommonDialogs;
import es.sonxurxo.gpsgame.client.cv.service.WaitUntilGameStartService;
import es.sonxurxo.gpsgame.client.cv.util.constants.CustomResultCodes;
import es.sonxurxo.gpsgame.client.model.service.game.HttpGameServiceImpl;
import es.sonxurxo.gpsgame.client.model.service.to.Game;
import es.sonxurxo.gpsgame.client.model.service.to.Player;
import es.sonxurxo.gpsgame.client.util.DateOperations;
import es.sonxurxo.gpsgame.client.util.db.PendingGamesDbAdapter;
import es.sonxurxo.gpsgame.client.util.exception.ServerException;

/**
 * 
 * @author "Xurxo Mendez Perez"
 *
 */
public class MainMenuActivity extends Activity implements Abandonable{

    private static final int CHANGE_PASSWORD_ID = Menu.FIRST;
    private static final int UPDATE_ID = Menu.FIRST + 1;
    private static final int VIEW_HISTORY_ID = Menu.FIRST + 2;
    private static final int FIND_GAMES_ID = Menu.FIRST + 3;
    private static final int LOGOUT_ID = Menu.FIRST + 4;

    private static final int FIND_GAMES_REQUEST_CODE = 0;
    private static final int VIEW_GAME_REQUEST_CODE = 1;
    private static final int VIEW_HISTORY_REQUEST_CODE = 2;
    private static final int CHANGE_PASSWORD_REQUEST_CODE = 3;
    private static final int UPDATE_INFO_REQUEST_CODE = 4;
    private static final int START_REQUEST_CODE = 5;  
    
    private static final int FIND_GAMES_DIALOG_ID = CommonDialogs.FIRST_CUSTOM_DIALOG_ID;;
    private static final int JOINED_DIALOG_ID = FIND_GAMES_DIALOG_ID + 1;
    private static final int GPS_OFF_DIALOG_ID = FIND_GAMES_DIALOG_ID + 2;

    private Game game;
    private Player player = new Player();

    private TextView loginView, totalPointsView, maxPointsView, bestRankView,
    gameIdView, countryView, emailView, phoneView, nameView, surnameView, 
    rightTitle, pressView;
    private Button gameInfoButton, playButton;
    private ImageView image;
    private ScrollView scrollView;
    
    private View gameLayout, gameTableView;

    private Animation hyperAnimation, hyperAnimationSlow;
    private LocationManager lm;
    private Location currentLocation;
    private String city = null;
    
    private FindGameTask findGameTask;
    private DbFetcherTask dbFetcherTask;
    private DbCreateTask dbCreateTask;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.player_info_page);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1);

        rightTitle = (TextView)findViewById(R.id.title_right_text);
    	loginView = (TextView)findViewById(R.id.pi_tv_login);
        emailView = (TextView)findViewById(R.id.pi_tv_email);
        phoneView = (TextView)findViewById(R.id.pi_tv_phone);
        nameView = (TextView)findViewById(R.id.pi_et_name);
        surnameView = (TextView)findViewById(R.id.pi_et_surname);
        countryView = (TextView)findViewById(R.id.pi_et_country);
        totalPointsView = (TextView)findViewById(R.id.pi_tv_totalpoints);
        maxPointsView = (TextView)findViewById(R.id.pi_tv_maxpoints);
        bestRankView = (TextView)findViewById(R.id.pi_tv_bestrank);
        image = (ImageView)findViewById(R.id.pi_image);
        
        scrollView = (ScrollView)findViewById(R.id.pi_scrollview);
        
        gameIdView = (TextView)findViewById(R.id.pi_tv_gameid);
        
        gameInfoButton = (Button)findViewById(R.id.pi_b_view_game_info);
        gameInfoButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				launchViewGameThread();
			}
        });

        pressView = (TextView)findViewById(R.id.pi_press);
        playButton = (Button)findViewById(R.id.pi_b_play_game);
        playButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null)
					launchPlayGameThread();
				else
					showDialog(GPS_OFF_DIALOG_ID);
			}
        });
        gameLayout = findViewById(R.id.game_layout);
        
        hyperAnimation = AnimationUtils.loadAnimation(this, R.anim.hyperspace_in);
        hyperAnimationSlow = 
        	AnimationUtils.loadAnimation(this, R.anim.hyperspace_in_slow);
        
        gameTableView = findViewById(R.id.pi_table);

        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
    			0, 0, new LocationListener() {
	
					public void onLocationChanged(Location location) {
						currentLocation = location;
					}
	
					public void onProviderDisabled(String provider) {
					}
	
					public void onProviderEnabled(String provider) {
					}
	
					public void onStatusChanged(String provider,
							int status, Bundle extras) {
					}
		});
        updateLocation();
    }
	
	@Override
	protected void onResume() {
		showDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
		super.onResume();
		scrollView.setSmoothScrollingEnabled(true);
		player = (Player)getIntent().getExtras().getSerializable("player");
        fillPersonalInfo();
        fillGameInfo();
        try {
        	dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
        } catch (Exception e) {
        	
        }
	}
	
	private void fillPersonalInfo() {
		image.setImageResource(player.getImageId());
		loginView.setText(player.getLogin());
        emailView.setText(player.getEmail());
        phoneView.setText(player.getPhone());
        nameView.setText(player.getName());
        surnameView.setText(player.getSurname());        
        countryView.setText(player.getCountry());        
        totalPointsView.setText(String.valueOf(player.getTotalPoints()));
        maxPointsView.setText(String.valueOf(player.getMaxPoints()));
        bestRankView.setText(String.valueOf(player.getBestRank()));
        rightTitle.setText(player.getLogin());
        
        gameTableView.startAnimation(
        		hyperAnimation);
	}

	private void fillIfJoinedThroughAnotherTerminal() {
		if (player.getGameId() != -1) {
			findGameTask = new FindGameTask(
					player.getGameId(), FindGameTask.GET_INFO_GOAL);
			Thread findGameThread = new Thread(null, findGameTask, "FindGame");
			findGameThread.start();
			showDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
			return;
		}
		else {
			scrollView.fullScroll(ScrollView.FOCUS_UP);
        	pressView.clearAnimation();
        	pressView.setVisibility(View.INVISIBLE);
        	playButton.setVisibility(View.INVISIBLE);
        	gameLayout.setVisibility(View.INVISIBLE);
			return;
		}
	}
	
	private void fillIfJoinedThroughThisTerminal(String sD, String fD) {
		if (player.getGameId() != -1) {
			gameLayout.startAnimation(hyperAnimation);
			gameIdView.setText(" " + String.valueOf(player.getGameId()));
	
	    	long startDate = DateOperations.formatString(sD).getTimeInMillis();
	    	long finishDate = DateOperations.formatString(fD).getTimeInMillis();
	    	long currentTime = System.currentTimeMillis();
	
	    	// Game did not started
	    	if (currentTime < startDate) {
	    		pressView.clearAnimation();
	    		scrollView.fullScroll(ScrollView.FOCUS_UP);
	    		pressView.setVisibility(View.INVISIBLE);
	    		playButton.setVisibility(View.INVISIBLE);
	    	}
	    	// Game is in play
	    	else if (currentTime <= finishDate - 30000) {
	    		scrollView.fullScroll(ScrollView.FOCUS_DOWN);
				playButton.setVisibility(View.VISIBLE);
	    		pressView.setVisibility(View.VISIBLE);
				hyperAnimationSlow.setRepeatCount(Animation.INFINITE);
				pressView.setAnimation(hyperAnimationSlow);
				pressView.startAnimation(hyperAnimationSlow);
	    	}
	    	// Game has finished
	    	else {
	    		scrollView.fullScroll(ScrollView.FOCUS_UP);
	    		pressView.setVisibility(View.INVISIBLE);
	    		playButton.setVisibility(View.INVISIBLE);
	    	}

	    	gameLayout.setVisibility(View.VISIBLE);
		}
		else {
			CommonActions.launchDbDeleteThread(player, this);
			scrollView.fullScroll(ScrollView.FOCUS_UP);
			pressView.clearAnimation();
        	pressView.setVisibility(View.INVISIBLE);
        	playButton.setVisibility(View.INVISIBLE);
        	gameLayout.setVisibility(View.INVISIBLE);
			return;
		}
	}

	private void fillGameInfo() {
		dbFetcherTask = new DbFetcherTask(player.getLogin());
		Thread dbThread = new Thread(null, dbFetcherTask, "Login");
		dbThread.start();
		showDialog(CommonDialogs.LOADING_DIALOG_ID);
	}
	
	private void doLaunchDbCreateThread() {
		dbCreateTask = new DbCreateTask(game);
		Thread dbCreateThread = new Thread(null, dbCreateTask, "DbCreate");
		dbCreateThread.start();
		showDialog(CommonDialogs.LOADING_DIALOG_ID);
	}

	private void doPlayGame() {
		Intent i = new Intent(this, MapViewActivity.class);
  	   	i.putExtra("player", player);
	    i.putExtra("game", game);
	   	startActivityForResult(i, START_REQUEST_CODE);
	}

	private void launchPlayGameThread() {
		findGameTask = new FindGameTask(player.getGameId(), 
				FindGameTask.START_GAME_GOAL);
		Thread findGameThread = new Thread(null, findGameTask, "Login");
		findGameThread.start();
		showDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
  	}

	private void updateLocation() {
    	try {

        	Geocoder gc = new Geocoder(this);

        	currentLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        	List<Address> lista = gc.getFromLocation(currentLocation.getLatitude(), 
        			currentLocation.getLongitude(), 1);

			city = lista.get(0).getLocality();
			
    	} catch (Exception e) {
    		Toast.makeText(this, 
    				getResources().getString(R.string.pi_get_location_error), 
    				Toast.LENGTH_LONG).show();
    	}
	}
	
	private void showToast(int messageId, int length) {
		Toast.makeText(this, messageId,
                length).show();
	}

	private void showToast(String message, int length) {
		Toast.makeText(this, message,
                length).show();
	}

	private void doLogout() {
		CommonActions.launchLogoutThread(player.getLogin(), this);
	}
	
	private void launchViewGameThread() {
		findGameTask = new FindGameTask(player.getGameId(), FindGameTask.VIEW_GAME_GOAL);
		Thread findGameThread = new Thread(null, findGameTask, "FindGame");
		findGameThread.start();
		showDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
	}

	private void doViewGame() {
		Intent i = new Intent(this, 
				ViewGameActivity.class);
	    i.putExtra("player", player);
	    i.putExtra("game", game);
		startActivityForResult(i, VIEW_GAME_REQUEST_CODE);
		try {
	   		dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
	   	} catch (Exception e) {
	   		
	   	}
	}
	
	private void doUpdateInfo() {
		Intent i = new Intent(this, UpdateInfoActivity.class);
		i.putExtra("player", player);
		startActivityForResult(i, UPDATE_INFO_REQUEST_CODE);		
	}

	public void doViewHistory() {

        Intent i = new Intent(this, ViewHistoryActivity.class);
        i.putExtra("player", player);
        startActivityForResult(i, VIEW_HISTORY_REQUEST_CODE);
	}
	
	public void doFindGames() {
		showDialog(FIND_GAMES_DIALOG_ID);
	}
	
	public void doChangePassword() {
		Intent i = new Intent(this, ChangePasswordActivity.class);
		i.putExtra("player", player);
	    startActivityForResult(i, CHANGE_PASSWORD_REQUEST_CODE);
	}

	private void doFindGames(int method) {

    	Intent i = new Intent(this, FindGamesActivity.class);;
    	i.putExtra("player", player);
		switch (method) {
		case FindGamesActivity.SEARCH_METHOD_CITY:
			i.putExtra("method", FindGamesActivity.SEARCH_METHOD_CITY);
			break;
		case FindGamesActivity.SEARCH_METHOD_THIS_CITY:
			i.putExtra("city", city);
			i.putExtra("method", FindGamesActivity.SEARCH_METHOD_THIS_CITY);
			break;
		case FindGamesActivity.SEARCH_METHOD_LOCATION:
			i.putExtra("location", currentLocation);
			i.putExtra("method", FindGamesActivity.SEARCH_METHOD_LOCATION);
			break;
		}
		startActivityForResult(i, FIND_GAMES_REQUEST_CODE);
    }	
		
	public void doAfterAbandon() {}

	@Override
    protected Dialog onCreateDialog(int id) {
		Dialog d = CommonDialogs.createDialog(id, this);
		if (d != null)
			return d;
    	switch(id) {
        case FIND_GAMES_DIALOG_ID:
        	CharSequence [] items;
        	if (city != null)
        		items = new CharSequence[]{"By city", "By distance", "Here, in " + city};
        	else 
        		items = new CharSequence[]{"By city"};

            return new AlertDialog.Builder(this)
            .setTitle(R.string.pi_find_games_choose)
            .setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                	int method = FindGamesActivity.SEARCH_METHOD_CITY;
                	if (which == 0)
                		method = FindGamesActivity.SEARCH_METHOD_CITY;
                	else if (which == 1)
                		method = FindGamesActivity.SEARCH_METHOD_LOCATION;
                	else if (which == 2)
                		method = FindGamesActivity.SEARCH_METHOD_THIS_CITY;
                    doFindGames(method);
                }
            })
            .create();
        case JOINED_DIALOG_ID:
        	return new AlertDialog.Builder(this)
            .setIcon(R.drawable.alert_dialog_icon)
            .setTitle(getString(R.string.pi_joined_to_game))
            .setPositiveButton(R.string.ok, null)
           .create();
        case GPS_OFF_DIALOG_ID:
        	return new AlertDialog.Builder(this)
            .setIcon(R.drawable.alert_dialog_icon)
            .setTitle(getString(R.string.pi_gps_off))
            .setPositiveButton(R.string.ok, null)
           .create();
		}
        return null;
    }
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, CHANGE_PASSWORD_ID,0, R.string.pi_b_change_password)
        	.setIcon(R.drawable.password);
        menu.add(0, UPDATE_ID,0, R.string.pi_b_update_info)
        	.setIcon(R.drawable.update);
        menu.add(0, VIEW_HISTORY_ID,0, R.string.pi_b_view_history)
        	.setIcon(R.drawable.history);
        menu.add(0, FIND_GAMES_ID,0, R.string.pi_b_find_games)
        	.setIcon(R.drawable.find);
        menu.add(0, LOGOUT_ID,0, R.string.pi_mo_logout)
        	.setIcon(R.drawable.logout);
        return true;
    }
	
	@Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case LOGOUT_ID:
        	doLogout();
        	break;
        case UPDATE_ID:
        	doUpdateInfo();
        	break;
        case CHANGE_PASSWORD_ID:
        	doChangePassword();
        	break;
        case VIEW_HISTORY_ID:
	    	doViewHistory();
	    	break;
	    case FIND_GAMES_ID:
	    	doFindGames();
	    	break;
	    }
        return super.onMenuItemSelected(featureId, item);
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == CustomResultCodes.LOGOUT_RESULT_CODE) {
			setResult(CustomResultCodes.LOGOUT_RESULT_CODE);
			finish();
			return;
		}
		switch (requestCode) {
		case FIND_GAMES_REQUEST_CODE:
			switch (resultCode) {
			case RESULT_OK:
				getIntent().putExtras(data.getExtras());
				game = (Game)data.getExtras().getSerializable("game");
				player = (Player)data.getExtras().getSerializable("player");
				removeDialog(FIND_GAMES_DIALOG_ID);

				long startTime = game.getStartDate().getTimeInMillis();
		    	long currentTime = System.currentTimeMillis();
		    	
		    	if (currentTime < startTime) {
		        	Intent i = new Intent(this, WaitUntilGameStartService.class);
		        	i.putExtra("player", player);
		        	i.putExtra("game", game);
		        	startService(i);
		        	showDialog(JOINED_DIALOG_ID);
		    	}
				break;
			case RESULT_CANCELED:
				try {
					removeDialog(FIND_GAMES_DIALOG_ID);
				} catch (Exception e) {
					
				}
				break;
			case CustomResultCodes.FG_NO_CITIES_RESULT_CODE:
				showToast(R.string.fg_no_cities, Toast.LENGTH_SHORT);
				break;
			case CustomResultCodes.VG_NO_GAMES_RESULT_CODE:
				showToast(R.string.vh_nogames, Toast.LENGTH_SHORT);
				break;
			}
			break;
		case VIEW_GAME_REQUEST_CODE:
			switch (resultCode) {
			case RESULT_OK:
				break;
			case CustomResultCodes.ABANDONED_RESULT_CODE:
				getIntent().putExtras(data.getExtras());
				player = (Player)data.getExtras().getSerializable("player");
				stopService(new Intent(this, WaitUntilGameStartService.class));
				((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).
					cancel(R.string.cancel);
				showToast(getString(R.string.vg_removed_from_game), 
						Toast.LENGTH_SHORT);
				break;
			}
			break;
		case VIEW_HISTORY_REQUEST_CODE:
			switch (resultCode) {
			case CustomResultCodes.VH_NO_GAMES_RESULT_CODE:
				showToast(R.string.vh_nogames, Toast.LENGTH_SHORT);
				break;
			}
			break;
		case CHANGE_PASSWORD_REQUEST_CODE:
			switch (resultCode) {
			case RESULT_OK:
				showToast(R.string.cp_changed, Toast.LENGTH_SHORT);
				break;
			}
			break;
		case UPDATE_INFO_REQUEST_CODE:
			switch (resultCode) {
			case RESULT_OK:
				getIntent().putExtras(data.getExtras());
				showToast(R.string.pi_updated, Toast.LENGTH_SHORT);
				break;
			}
			break;
		case START_REQUEST_CODE:
			try {
				dismissDialog(JOINED_DIALOG_ID);
			} catch (IllegalArgumentException e) {
				
			}
			switch (resultCode) {
			case CustomResultCodes.ABANDONED_RESULT_CODE:
				Toast.makeText(this, "You have abandoned.", Toast.LENGTH_SHORT).show();
				getIntent().putExtras(data.getExtras());
				break;
			case CustomResultCodes.GAME_FINISHED_RESULT_CODE:
				getIntent().putExtras(data.getExtras());
				player = (Player)data.getExtras().getSerializable("player");
				long gameId = data.getExtras().getLong("gameId");

				Intent i = new Intent(this, ViewHistoryActivity.class);
		        i.putExtra("player", player);
		        i.putExtra("gameId", gameId);
		        startActivityForResult(i, VIEW_HISTORY_REQUEST_CODE);
				break;
			}
			break;
		}
	}
	
	private class FindGameHandler extends Handler {

		public FindGameHandler(Looper looper) {
			super(looper);
		}
		
		@Override
		public void handleMessage(Message msg) {
			try {
				dismissDialog(CommonDialogs.CONNECTING_TO_SERVER_DIALOG_ID);
			} catch (Exception e) {
				
			}
			ServerException sE = 
				(ServerException)msg.getData().getSerializable("ServerException");
			if (sE	!= null) {
				CommonDialogs.errorMessage = sE.getMessage();
	        	showDialog(CommonDialogs.SERVER_ERROR_DIALOG_ID);
	        	return;
	        }
        	Exception e = 
	        	(Exception)msg.getData().getSerializable("Exception");
	        	if (e != null) {
	        		CommonDialogs.errorMessage = e.getLocalizedMessage();
		        	showDialog(CommonDialogs.CLIENT_ERROR_DIALOG_ID);
		        	return;
	        	}
	        Game gameP = (Game)msg.getData().getSerializable("game");
	        if (gameP != null) {
	        	game = gameP;

	        	switch (msg.getData().getInt("goal")) {
	        	case FindGameTask.START_GAME_GOAL:
	        		doPlayGame();
	        		break;
	        	case FindGameTask.VIEW_GAME_GOAL:
	        		doViewGame();
	        		break;
	        	case FindGameTask.GET_INFO_GOAL:
	        		doLaunchDbCreateThread();
	        		break;
	        	}
	        }
		}
		
	}
	
	private class FindGameTask implements Runnable {

		public static final int VIEW_GAME_GOAL = 0;
		public static final int START_GAME_GOAL = 1;
		public static final int GET_INFO_GOAL = 2;
		
		int goal;
		String gameIdString;
		HttpGameServiceImpl gameService;
		
		FindGameTask(long gameId, int goal) {
			this.gameIdString = String.valueOf(gameId);
			this.goal = goal;
			gameService = new HttpGameServiceImpl();
		}
		
		public void run() {
			
			FindGameHandler handler = new FindGameHandler(Looper.getMainLooper());
			Bundle data = new Bundle();
			Message msg = new Message();
			try {
				Game game = gameService.findGame(gameIdString);
				data.putSerializable("game", game);
				data.putInt("goal", goal);
				msg.setData(data);
				handler.sendMessage(msg);
				
			} catch (ServerException e) {
	        	data.putSerializable("ServerException", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
	        } catch (Exception e) {
	        	data.putSerializable("Exception", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
	        }
		}
	}
	
	private class DbHandler extends Handler {

		public DbHandler(Looper looper) {
			super(looper);
		}
		
		@Override
		public void handleMessage(Message msg) {
			dismissDialog(CommonDialogs.LOADING_DIALOG_ID);
			SQLiteException e = 
	        	(SQLiteException)msg.getData().getSerializable("SQLiteException");
	        	if (e != null) {
	        		CommonDialogs.errorMessage = e.getLocalizedMessage();
		        	showDialog(CommonDialogs.SQLITE_ERROR_DIALOG_ID);
		        	return;
	        	}
	        
	        String startDate = msg.getData().getString("startDate");
	        if (startDate != null) {
	        	String finishDate = msg.getData().getString("finishDate");
	        	fillIfJoinedThroughThisTerminal(startDate, finishDate);
	        }
	        if (msg.getData().getBoolean("noRegister")) {
	        	fillIfJoinedThroughAnotherTerminal();
			}
		}
	}
	
	private class DbFetcherTask implements Runnable {

		String login;
		private PendingGamesDbAdapter p = new PendingGamesDbAdapter(MainMenuActivity.this);
		
		DbFetcherTask(String login) {
			this.login = login;
		}
		
		public void run() {
			
			DbHandler handler = new DbHandler(Looper.getMainLooper());
			Bundle data = new Bundle();
			Message msg = new Message();
			try {
	        	p.open();
	        	Cursor c = p.fetchPendingGame(login);
	    		if (c.getCount() != 0) {
	    			String sD = c.getString(
	    					c.getColumnIndex(PendingGamesDbAdapter.KEY_START_DATE));
	    			String fD = c.getString(
	    					c.getColumnIndex(PendingGamesDbAdapter.KEY_FINISH_DATE));
	    			p.close();
	    			data.putString("startDate", sD);
		        	data.putString("finishDate", fD);
					msg.setData(data);
					handler.sendMessage(msg);
					return;
	    		}
	    		else {
	    			p.close();
		        	data.putBoolean("noRegister", true);
					msg.setData(data);
					handler.sendMessage(msg);	    			
	    		}
			} catch (SQLiteException e) {
				data.putSerializable("SQLiteException", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
			}
		}
	}
	
	private class DbCreateHandler extends Handler {

		public DbCreateHandler(Looper looper) {
			super(looper);
		}
		
		@Override
		public void handleMessage(Message msg) {
			try {
				dismissDialog(CommonDialogs.LOADING_DIALOG_ID);
			} catch(Exception e) {
				
			}
			SQLiteException e = 
	        	(SQLiteException)msg.getData().getSerializable("SQLiteException");
	        	if (e != null) {
	        		CommonDialogs.errorMessage = e.getLocalizedMessage();
		        	showDialog(CommonDialogs.SQLITE_ERROR_DIALOG_ID);
		        	return;
	        	}
			Game game = (Game)msg.getData().getSerializable("game");
			if (game != null)
				fillIfJoinedThroughThisTerminal(DateOperations.formatDate(game.getStartDate()),
			    		DateOperations.formatDate(game.getFinishDate()));
		}
	}
	
	private class DbCreateTask implements Runnable {

		Game game;
		PendingGamesDbAdapter p = new PendingGamesDbAdapter(MainMenuActivity.this);
		DbCreateTask(Game game) {
			this.game = game;
		}
		
		public void run() {
			
			DbCreateHandler handler = new DbCreateHandler(Looper.getMainLooper());
			Bundle data = new Bundle();
			Message msg = new Message();
			try {
	        	p.open();
	        	p.createPendingGame(player.getLogin(), game.getGameId(),
	        			DateOperations.formatDate(game.getStartDate()),
	        			DateOperations.formatDate(game.getFinishDate()));
	        	p.close();
	        	data.putSerializable("game", game);
				msg.setData(data);
				handler.sendMessage(msg);
			} catch (SQLiteException e) {
				data.putSerializable("SQLiteException", e);
	        	msg.setData(data);
				handler.sendMessage(msg);
			}
		}
	}
}
